﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace Odyssey.Controls
{

    public interface IWeakPropertyChangedEventListener
    {
        void OnPropertyChanged(object sender, PropertyChangedEventArgs e);
    }

    public class WeakNotifyPropertyChangedListener
    {
        private INotifyPropertyChanged source;
        private WeakReference weakListener;

        private WeakNotifyPropertyChangedListener(INotifyPropertyChanged source, IWeakPropertyChangedEventListener listener)
        {
            this.source = source;
            this.source.PropertyChanged+=this.SourceCollectionChanged;
            this.weakListener = new WeakReference(listener);
        }

        public static WeakNotifyPropertyChangedListener CreateIfNecessary(object source, IWeakPropertyChangedEventListener listener)
        {
            if (source is INotifyPropertyChanged)
            {
                return new WeakNotifyPropertyChangedListener(source as INotifyPropertyChanged, listener);
            }
            return null;
        }

 

        /// <summary>
        /// Disconnects the listener from the event.
        /// </summary>
        public void Disconnect()
        {
            if (this.source != null)
            {
                this.source.PropertyChanged -= SourceCollectionChanged;
                this.source = null;
                this.weakListener = null;
            }
        }

        private void SourceCollectionChanged(object sender, PropertyChangedEventArgs e)
        {
            if (this.weakListener != null)
            {
                IWeakPropertyChangedEventListener target = this.weakListener.Target as IWeakPropertyChangedEventListener;
                if (target != null)
                {
                    target.OnPropertyChanged(sender, e);
                }
                else
                {
                    this.Disconnect();
                }
            }
        }



    }
}
